<template>
	<view class="reservation-box w100">

		<!-- 助教信息 -->
		<view class="assistant-info w100 flex-row-center">
			<view class="userinfo-box flex-row-center w100">
				<up-avatar shape="circle" :src="assistantInfo.avatar" mode="aspectFill" size="98rpx"></up-avatar>
				<view class="info-box flex">
					<view class="flex-row-center">
						<text class="name">{{assistantInfo.nickname}}</text>
						<template>
							<up-icon name="man" v-if="assistantInfo.gender==1" color="#2979ff" size="28rpx"></up-icon>
							<up-icon name="woman" v-if="assistantInfo.gender==2" color="#FFC0CB" size="28rpx"></up-icon>
						</template>
					</view>
					<view class="info-footer flex-row-center w100">
						<view class="info-lv" v-if="assistantInfo.level_name">
							<text class="tag">{{assistantInfo.level_name}}助教</text>
						</view>
						<text
							class="assistant-price">￥{{assistantInfo.assistant_price}}/{{assistantInfo.time_unit}}分钟</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 地址 -->
		<view class="address-box w100 flex-row-center">
			<view class="icon-box flex-center">
				<up-icon name="map-fill" color="#72C1B1" size="38rpx"></up-icon>
			</view>
			<view class="address-info flex" @click="toChoose">
				<text class="name" v-if="reservationInfo.addressId">{{reservationInfo.address}}</text>
				<text class="name" v-else>请选择预约地址</text>
				<!-- <text class="address">四川省遂宁市安居区三加征啥看法和端口是否还是看</text> -->
			</view>
			<view class="address-right flex-row-center">
				<up-icon name="arrow-right" color="#E4E4E5" size="38rpx"></up-icon>
			</view>
		</view>
		<!-- 地址 -->
		<!-- 		<view class="address-box w100 flex-row-center">
			<view class="from-item flex-row-center">
				<text class="from-name">地址填写</text>
				<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx" color="#DEDEDE"
					placeholder="请输入内容" v-model="reservationInfo.address">
					<template #suffix>
						<up-icon @click="chooseLocationTap" name="map-fill" color="#DEDEDE" size="42rpx"></up-icon>
					</template>
				</up-input>
			</view>
		</view> -->
		<!-- 预约时间 -->
		<view class="from-content">
			<view class="from-item flex-row-center">
				<text class="from-name">预约时间</text>
				<view class="example-body flex-row-center">
					<view class="example-item" @click="datetimeStartShow=true">
						<up-input inputAlign="right" border="none" disabled placeholderClass="placeholderClass"
							fontSize="26rpx" color="#DEDEDE" placeholder="请选择开始时间"
							v-model="reservationInfo.startTime"></up-input>
					</view>
					<text class="example-icon">-</text>
					<view class="example-item" @click="datetimeEndShow=true">
						<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx"
							color="#DEDEDE" placeholder="请选择结束时间" v-model="reservationInfo.endTime"></up-input>
					</view>
				</view>
			</view>
		</view>
		<!-- 路费 -->
		<view class="tolls-box" v-if="calculateDistanceInfo">
			<view class="name-box flex-row-center">
				<text class="name">往返路费</text>
				<text class="price">￥{{calculateDistanceInfo.distant_amount}}</text>
			</view>
			<!-- 。<text class="btn">查看计费规则</text> -->
			<text class="detail">全程共{{calculateDistanceInfo.distance}}km。<text v-if="payTips">{{payTips}}</text> </text>
		</view>
		<!-- 支付方式 -->
		<view class="pay-type">
			<choosePayVue :payType="reservationInfo.payType" @changePayType="changePayType" style="width: 100%;">
			</choosePayVue>
		</view>
		<!-- 底部操作 -->
		<view class="assistant-footer w100">
			<view class="footer-content w100 flex-row-center">
				<view class="total-box flex-row-center">
					<!-- 	<text class="text">合计：</text>
					<text class="price">￥99.99</text> -->
				</view>
				<up-button text="确认预约" @click="submitReservation" loadingText="提交中" :loading="reservationInfo.loading"
					:customStyle="{'color':'#115B56',height:'64rpx',margin:'0',width:'240rpx'}"
					color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)" shape="circle"></up-button>
			</view>
		</view>
	</view>
	<!-- 弹出组队 -->
	<up-popup :show="addressShow" @close="closeAddressShow" round="18rpx" closeable mode="bottom">
		<view class="choose-sign flex w100">
			<text class="title">选择预约地址</text>
			<template v-if="addressInfo.list.length>0">
				<view class="choose-content W100">
					<scroll-view scroll-y="true" style="height: 100%;width: 100%;" @scrolltolower="getMoreList">
						<view class="sign-item flex-row-center W100" v-for="(item,index) in addressInfo.list"
							:key="item.id" @click="changeAddressId(item)">
							<view class="personnel-left">
								<view class="radio-box-active flex-center" v-if="reservationInfo.addressId==item.id">
									<up-icon name="checkbox-mark" color="#0A534F" size="28rpx"></up-icon>
								</view>
								<view class="radio-box" v-else></view>
							</view>
							<view class="personnel-right">
								<view class="personnel-head flex-row-center">
									<view class="name-box flex-row-center">
										<text class="name">{{item.address}}</text>
									</view>
									<view class="status-box flex-center" v-if="item.default">
										<text class="text">默认</text>
									</view>
								</view>
							</view>
						</view>
						<view class="view-more" @click="getMoreList">
							<up-loadmore :status="addressInfo.status" />
						</view>
					</scroll-view>
				</view>
			</template>
			<view class="not-list-view" v-else>
				<text class="text">暂未添加地址信息~</text>
				<text class="btn" style="margin-left: 8rpx;" @click="addAddress">立即添加</text>
			</view>
			<view class="choseSign-footer w100 flex-center">
				<view class="add_box flex-center" @click="addAddress">
					<up-icon name="plus" color="#7CDEC7" size="28rpx"></up-icon>
					<text class="text">新增地址</text>
				</view>
			</view>
		</view>
	</up-popup>
	<!-- 时间选择组件 -->
	<up-datetime-picker :minDate="nowTime" @cancel="datetimeStartShow=false" v-model="nowTime" :formatter="formatter"
		title="组队开始时间" :show="datetimeStartShow" @confirm="confirmStartTime" mode="datetime"></up-datetime-picker>
	<up-datetime-picker :formatter="formatter" title="组队结束时间" :minDate="nowTime" @cancel="datetimeEndShow=false"
		v-model="nowTime" :show="datetimeEndShow" @confirm="confirmEndTime" mode="datetime"></up-datetime-picker>
</template>

<script setup>
	import {
		usePay
	} from '@/hooks/usePay.js';
	import choosePayVue from '@/components/choosePay/choosePay.vue';
	import {
		formatDate,
		countDecimalPlaces,
		toDecimal2
	} from '@/utils/utools.js';
	import {
		assistantStore
	} from '@/stores/assistant.js';
	import {
		chooseLocation
	} from '@/utils/chooseLocation';
	import {
		assistantNotification
	} from '@/utils/assistantNotification.js';
	import {
		configInfoStore
	} from '@/stores/config';
	const {
		configInfo
	} = configInfoStore();
	const payTips = computed(() => {
		let tips =
			`收费标准：${configInfo.basic_mileage.title}${configInfo.basic_mileage.value}km，收取${configInfo.basic_mileage_price.value}元，超过${configInfo.basic_mileage.title}，每公里增收${configInfo.exceed_price.value}元`
		return tips
	})
	const {
		appPay
	} = usePay();
	const formatter = (type, value) => {
		if (type === 'year') {
			return `${value}年`;
		}
		if (type === 'month') {
			return `${value}月`;
		}
		if (type === 'day') {
			return `${value}日`;
		}
		if (type === 'hour') {
			return `${value}时`;
		}
		if (type === 'minute') {
			return `${value}分`;
		}
		return value;
	};
	const nowTime = Date.now(); //当前时间
	const assistantInfoStore = assistantStore();
	const assistantInfo = ref(computed(() => assistantInfoStore.assistantItemInfo));
	const datetimeStartShow = ref(false);
	const datetimeEndShow = ref(false);
	const addressShow = ref(false);
	const orderInfo = ref(null);
	const assistantId = ref(0);
	const calculateDistanceInfo = ref(null)
	const reservationInfo = reactive({
		startTime: '',
		endTime: '',
		endTimestamp: 0,
		startTimestamp: 0,
		address: '',
		lat: 0,
		lng: 0,
		addressId: 0,
		loading: false,
		payType: 'wechat'
	});
	const addressInfo = reactive({
		page: 1,
		list: [],
		status: 'loadmore'
	});
	onLoad((option) => {
		if (option.id) {
			assistantId.value = option.id;
		}
	});
	onMounted(() => {
		uni.$on('addAddress', (data) => {
			console.log('监听到事件来自 addSign ，携带参数 msg 为：', data);
			if (data.type) {
				restData()
				getAddressList();
			}
		})
	})
	const changePayType = (item) => { //切换支付方式
		reservationInfo.payType = item;
	}
	const getMoreList = () => {
		if (addressInfo.status === 'loading' || addressInfo.status === 'nomore') return
		addressInfo.status = 'loading';
		setTimeout(() => {
			getAddressList();
		}, 300)
	}
	const closeAddressShow = () => {
		addressShow.value = false;
		restData()
	}
	const toChoose = async () => {
		getAddressList();
		addressShow.value = true;
	}
	const restData = () => {
		addressInfo.list = [];
		addressInfo.page = 1
		addressInfo.status = 'loadmore'
	}
	const getAddressList = async () => { //获取地址列表
		const res = await $Api.address.getList({
			page: addressInfo.page
		});
		if (res.code == 1) {
			res.data.list = res.data.list.map(val => {
				let first_name = '北';
				if (val.address) {
					first_name = val.address.charAt(0);
				}
				return {
					...val,
					first_name
				}
			})
			if (res.data.totalPage > addressInfo.page) {
				addressInfo.status = 'loadmore'
			} else {
				addressInfo.status = 'nomore'
			}

			addressInfo.list = [...addressInfo.list, ...res.data.list];
		} else {
			uni.$u.toast(res.msg);
		}
	}
	const confirmStartTime = (e) => { //选择开始时间
		if (e.value) {
			if (reservationInfo.endTimestamp && reservationInfo.endTimestamp <= e.value) {
				uni.$u.toast('请选择小于预约的结束时间');
				return
			}
			reservationInfo.startTimestamp = e.value;
			reservationInfo.startTime = formatDate(e.value, 'yyyy-MM-dd hh:mm');
			datetimeStartShow.value = false;
		}
	}
	const confirmEndTime = (e) => { //选择结束时间
		if (e.value) {
			if (reservationInfo.startTimestamp && reservationInfo.startTimestamp >= e.value) {
				uni.$u.toast('请选择大于预约的开始时间');
				return
			}
			reservationInfo.endTimestamp = e.value;
			reservationInfo.endTime = formatDate(e.value, 'yyyy-MM-dd hh:mm');
			datetimeEndShow.value = false;
		}
	}
	const addAddress = () => {
		uni.navigateTo({
			url: '/page_user/views/userAddress'
		})
	}
	const changeAddressId = (item) => { //切换名片
		// chooseSignId.value = item.id;
		reservationInfo.addressId = item.id;
		reservationInfo.address = item.address;
		closeAddressShow();
	};
	const calculateDistance = async (id) => {
		const res = await $Api.address.calculateDistance({
			addressId: id,
			assistantId: assistantId.value
		});
		if (res.code == 1) {
			calculateDistanceInfo.value = res.data;
		} else {
			uni.$u.toast(res.msg)
		}
	}
	const submitReservation = async () => { //提交预约
		if (reservationInfo.startTime == '') {
			uni.$u.toast('请选择开始时间')
			return
		}
		if (reservationInfo.endTime == '') {
			uni.$u.toast('请选择结束时间')
			return
		}
		if (!reservationInfo.addressId) {
			uni.$u.toast('请选择预约地址')
			return
		}
		reservationInfo.loading = true;
		const res = await $Api.order.submitOrder({
			type: 'wechat',
			method: 'miniapp',
			isBalance: reservationInfo.payType === 'balance' ? 1 : 0,
			relationType: 'Assistant',
			orderId: orderInfo.value?.id || 0,
			assistantIds: assistantId.value || '',
			startTime: reservationInfo.startTime,
			endTime: reservationInfo.endTime,
			addressId: reservationInfo.addressId,
		})
		if (res.code == 1) {
			const {
				data
			} = res;
			if (data.order) {
				data.order.time_expire = formatDate(data.order.time_expire);
				orderInfo.value = data.order;
				console.log('orderInfo.value', orderInfo.value);
			}
			if (reservationInfo.payType === 'balance') { //余额支付
				uni.showToast({
					title: '支付成功'
				})
				allNotification(['groupStart', 'groupClose', 'groupEnd'], () => {
					setTimeout(() => {
						reservationInfo.loading = false;
						uni.navigateBack()
					}, 600)
				}); //打开通知
			} else { //微信支付
				appPay({
					provider: 'wxpay',
					timeStamp: data.pre_payment.timeStamp,
					nonceStr: data.pre_payment.nonceStr,
					package: data.pre_payment.package,
					signType: data.pre_payment.signType,
					paySign: data.pre_payment.paySign,
				}).then((res) => {
					console.log(res);
					if (res.code == 200) {
						uni.showToast({
							title: '支付成功'
						});
						allNotification(['groupStart', 'groupClose', 'groupEnd'],
							() => {
								setTimeout(() => {
									reservationInfo.loading = false;
									uni.navigateBack()
								}, 600)
							}); //打开通知

					} else if (res.code == 100) { //取消支付
						uni.$u.toast('已取消支付，请10s后重新支付');
						reservationInfo.loading = false;
					}
				}).catch((err) => {
					// console.log(err);
					reservationInfo.loading = false;
					uni.$u.toast(err)
				})
			}

		} else {
			reservationInfo.loading = false;
			uni.$u.toast(res.msg)
		}
	}
	const chooseLocationTap = async () => { //选择地理位置
		uni.showLoading({
			title: '加载中'
		})
		chooseLocation('', '', true).then((res) => {
			uni.hideLoading();
			if (res) {
				reservationInfo.address = res.address + (res.name ? res.name : '');
				reservationInfo.lat = res.latitude;
				reservationInfo.lng = res.longitude;
			}
		}).catch(() => {
			uni.hideLoading();
			uni.$u.toast('获取位置失败');
		})
	}
	watch(() => reservationInfo.addressId, (newVal) => {
		if (newVal) {
			calculateDistance(newVal)
		}
	})
</script>

<style lang="scss" scoped>
	.reservation-box {
		padding: 32rpx 24rpx;
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
	}

	.assistant-info {
		margin-bottom: 24rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #222528;
		position: relative;
		justify-content: space-between;

		.info-right {
			flex-shrink: 0;
			flex-direction: column;
			height: 100%;
			justify-content: space-between;
			margin-left: 20rpx;

			.edit-info {
				margin-bottom: 24rpx;

				.text {
					color: $description-color;
					font-size: 28rpx;
					margin-right: 8rpx;
				}
			}
		}

		.userinfo-box {
			.info-box {
				flex: 1;
				width: 0;
				flex-direction: column;
				margin-left: 20rpx;

				.info-footer {
					justify-content: space-between;

					.assistant-price {
						color: $price-color;
						font-size: 28rpx;
						font-weight: bold;
					}
				}

				.name {
					color: $name-color;
					font-size: 32rpx;
					font-weight: 600;
					margin-right: 6rpx;
				}

				.info-lv {
					margin-top: 10rpx;

					.tag {
						background: #ff9900;
						color: #fff;
						padding: 4rpx 10rpx;
						border-radius: 8rpx;
						font-size: 24rpx;
					}
				}
			}
		}
	}

	.address-box {
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #222528;

		.icon-box {
			border-radius: 50%;
			background-color: #556360;
			width: 88rpx;
			height: 88rpx;
		}

		.address-info {
			flex: 1;
			width: 0;
			flex-direction: column;
			margin-left: 16rpx;

			.name {
				font-size: 30rpx;
				font-weight: bold;
				color: $name-color;
			}

			.address {
				font-size: 28rpx;
				color: $description-color;
				margin-top: 8rpx;
			}
		}
	}

	.from-content {
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #222528;
	}

	.from-item {
		box-sizing: border-box;
		width: 100%;

		::v-deep.placeholderClass {
			color: #5B6868 !important;
			font-size: 26rpx;
			font-weight: 500;
		}

		.from-name {
			display: block;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin-right: 38rpx;
			flex-shrink: 0;
		}

		.example-icon {
			font-size: 28rpx;
			color: #fff;
			margin: 0 24rpx;
		}

		.from-item-right {
			flex: 1;
		}

		.up-textarea-box {
			color: #fff;
		}
	}

	.tolls-box {
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #222528;
		display: flex;
		flex-direction: column;

		.name-box {
			justify-content: space-between;
		}

		.name {
			display: block;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
		}

		.price {
			font-weight: bold;
			font-size: 30rpx;
			color: $price-color;
		}

		.detail {
			font-size: 28rpx;
			margin-top: 12rpx;
			color: $description-color;
		}

		.btn {
			color: $attention-color;
		}
	}

	.pay-type {
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #222528;
	}

	.assistant-footer {
		width: 750rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #191C1F;
		border-top: 2rpx solid #303335;
		padding-bottom: env(safe-area-inset-bottom);

		.footer-content {
			height: 88rpx;
			justify-content: space-between;
			padding: 0 24rpx;

			.total-box {
				.text {
					color: $name-color;
					font-size: 28rpx;
				}

				.price {
					color: $price-color;
					font-size: 28rpx;
				}
			}

			.reservation-btn {
				height: 64rpx;
				border-radius: 32rpx;
				width: 180rpx;
				background: $btn-bg-color;

				.text {
					font-size: 26rpx;
					color: $btn-text-color;
				}
			}
		}
	}

	.choose-sign {
		padding: 36rpx;
		height: 60vh;
		flex-direction: column;
		flex-direction: column;
		background-color: #222528;
		border-radius: 18rpx 18rpx 0 0;

		.title {
			font-weight: bold;
			font-size: 34rpx;
			color: rgba(255, 255, 255, 0.87);
			line-height: 40rpx;
		}

		.choose-content {
			flex: 1;
			margin: 24rpx 0;
			overflow: hidden;

			.sign-item {
				padding: 20rpx 0;

				&:not(:last-child) {
					border-bottom: 1rpx solid #373B3E;
				}
			}
		}

		.radio-box {
			width: 36rpx;
			height: 36rpx;
			border-radius: 50%;
			border: 1rpx solid #ccc;
			margin-right: 18rpx;
			box-sizing: border-box;
		}

		.radio-box-active {
			width: 36rpx;
			height: 36rpx;
			border-radius: 50%;
			background-color: #7EDE9E;
			margin-right: 18rpx;
		}

		.choseSign-footer {
			height: 72rpx;
			justify-content: space-evenly;
		}

		.add_box {
			width: 280rpx;
			height: 68rpx;
			border-radius: 47rpx;
			border: 2rpx solid $btn-plain-color;

			.text {
				font-weight: 800;
				font-size: 30rpx;
				color: $btn-plain-color;
				margin-left: 12rpx;
			}
		}

		.personnel-left {
			flex-shrink: 0;
		}

		.personnel-right {
			margin-left: 24rpx;
			flex: 1;
			display: flex;
			flex-direction: column;
		}

		.personnel-head {
			width: 100%;
			justify-content: space-between;

			.name {
				font-size: 32rpx;
				font-weight: bold;
				color: $title-color;
				margin-right: 12rpx;
			}
		}

		.phone {
			color: $description-color;
			font-size: 28rpx;
			margin-top: 18rpx;
		}

		.status-box {
			width: 96rpx;
			height: 48rpx;
			border-radius: 12rpx;
			border: 1rpx solid $attention-color;
			color: $attention-color;
			align-self: flex-start;
			flex-shrink: 0;

			.text {
				color: $attention-color;
				font-weight: bold;
				font-size: 28rpx;
			}
		}
	}
</style>
<style>
	.u-textarea__count,
	.u-input,
	.u-textarea {
		padding: 0 !important;
		background-color: transparent !important;
	}

	.placeholderClass {
		color: #5B6868 !important;
		font-size: 26rpx;
		font-weight: 500;
	}

	.u-textarea__field {
		color: #fff !important;
	}
</style>